//Aurélien Prévot - MIT License//
//More information : https://jpbi.codeplex.com
//Blog post to use this with SharePoint Add Ins : https://rockwithazure.wordpress.com/2015/12/06/100-js-embed-power-bi-tiles/
//2016 -jpbi-0.1.0b.js

//**********************//
//***TILE MANAGEMENT***//
//********************//
function updateEmbedTile(iFrameId, embedTileUrl, h, w, clientAppId) {

    // check if the embed url was selected
    if ("" === embedTileUrl)
        return;

    // to load a tile do the following:
    // 1: set the url, include size.
    // 2: add a onload handler to submit the auth token
    iframe = document.getElementById(iFrameId);
    iframe.src = embedTileUrl + "&width=" + w + "&height=" + h;
    iframe.onload = function () { postActionLoadTile(iFrameId, h, w); }
}
function postActionLoadTile(iFrameId, h, w, clientAppId) {

    // construct the push message structure
    var m = { action: "loadTile", accessToken: requestToken(clientAppId), height: h, width: w };
    message = JSON.stringify(m);
    // push the message.
    iframe = document.getElementById(iFrameId);
    iframe.contentWindow.postMessage(message, "*");;
}

//*************************//
//***REPORTS MANAGEMENT***//
//***********************//
function updateEmbedReport(iFrameId, embedReportUrl, clientAppId) {
    // check if the embed url was selected
    if ("" === embedReportUrl)
        return;

    // to load a tile do the following:
    // 1: set the url, include size.
    // 2: add a onload handler to submit the auth token
    var iframe = document.getElementById(iFrameId);
    iframe.src = embedReportUrl;
    iframe.onload = function () { postActionLoadReport(iFrameId, clientAppId); }
}
function postActionLoadReport(iFrameId, clientAppId) {
    
    // construct the push message structure
    var m = { action: "loadReport", accessToken: requestToken(clientAppId) };
    message = JSON.stringify(m);
    // push the message.
    iframe = document.getElementById(iFrameId);
    iframe.contentWindow.postMessage(message, "*");
}

//************************//
//********UTILS**********//
//**********************//
function requestToken(clientAppId) {

    if (urlParameterExtraction.queryStringParameters['access_token'] == null) {

        // Change clientId and replyUrl to reflect your app's values
        // found on the Configure tab in the Azure Management Portal.
        var resource = 'https://analysis.windows.net/powerbi/api';
        var authServer = 'https://login.windows.net/common/oauth2/authorize?';
        var responseType = 'token';

        var url = authServer +
                  "response_type=" + encodeURI(responseType) + "&" +
                  "client_id=" + encodeURI(clientAppId) + "&" +
                  "resource=" + encodeURI(resource) + "&" +
                  "redirect_uri=" + encodeURI(window.location.href);

        window.location = url;
    }
    else {
        return urlParameterExtraction.queryStringParameters['access_token'];
    }
}

//***
//URL EXTRACTION
var urlParameterExtraction = new (function () {
    function splitQueryString(queryStringFormattedString) {
        var split = queryStringFormattedString.split('&');

        // If there are no parameters in URL, do nothing.
        if (split == "") {
            return {};
        }

        var results = {};

        // If there are parameters in URL, extract key/value pairs.
        for (var i = 0; i < split.length; ++i) {
            var p = split[i].split('=', 2);
            if (p.length == 1)
                results[p[0]] = "";
            else
                results[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }

        return results;
    }

    // Split the query string (after removing preceding '#').
    this.queryStringParameters = splitQueryString(window.location.hash.substr(1));
})();